using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OpenIddict.Validation.AspNetCore;

namespace Net8.Identity.WebClient.Extensions
{
    public static class RegisterServices
    {
        public static WebApplicationBuilder SetupServices(this WebApplicationBuilder builder)
        {
            // 从配置文件中读取密钥
            var openIddictIssuer = builder.Configuration["OpenIddict:Issuer"] ?? "https://localhost:7031/"; // 颁发者
            var openIddictAudience = builder.Configuration["OpenIddict:Audience"] ?? "resource_server_1"; // 接收者
            var encryptionKey = builder.Configuration["Jwt:EncryptionKey"] ?? "Qwl6q6Xj0Cf0S09jM43mQ5r3L2dH6vF4N8sP7eR3tE0=";

            builder.Services.AddControllers();
            builder.Services.AddOpenIddict()
                .AddValidation(options =>
                {
                    options.SetIssuer(openIddictIssuer);
                    options.AddAudiences(openIddictAudience);
                    
                    options.AddEncryptionKey(new SymmetricSecurityKey(
                            Convert.FromBase64String(encryptionKey)));
                    
                    options.UseSystemNetHttp();
                    options.UseAspNetCore();
                });

            builder.Services.AddAuthentication(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
            builder.Services.AddAuthorization();

            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{openIddictIssuer}oauth/authorize"),
                            TokenUrl = new Uri($"{openIddictIssuer}oauth/token"),
                            Scopes = new Dictionary<string, string>
                            {
                                { "openid", "请求基本的用户身份信息" },
                                { "api1", "访问 API 资源" }
                            }
                        },
                    }
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                        },
                        Array.Empty<string>()
                    }
                });
            });

            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowSwagger", policy =>
                {
                    policy.WithOrigins("https://localhost:7002")
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .AllowCredentials();
                });
            });

            return builder;
        }
    }
}